package com.meitianhui.convenitenbuy.module.store.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.main.model.bean.UserToken;
import com.meitianhui.convenitenbuy.module.mine.model.UserAsset;
import com.meitianhui.convenitenbuy.module.store.contract.ShopCarPayContract;
import com.meitianhui.convenitenbuy.module.store.di.DaggerStoreComponent;
import com.meitianhui.convenitenbuy.module.store.di.StoreModule;
import com.meitianhui.convenitenbuy.module.store.model.ShopCarGoods;
import com.meitianhui.convenitenbuy.module.store.presenter.ShopCarPayPresenter;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.StringUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.PasswordDialog;

import java.util.List;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.meitianhui.convenitenbuy.R.id.tv_number;

/**
 * Created by Administrator on 2017/11/27.
 * 购物车支付
 */

public class ShopCarPayActivity extends BaseToolbarActivity implements ShopCarPayContract.View, RadioGroup.OnCheckedChangeListener,PasswordDialog.OnDialogPsdCompleteListener {
    private RadioGroup mRgOrderPay;
    private int mPayWay = 0;//默认钱包支付
    private String mStoreId;
    private String mStoreName;
    private String mStoreAddress;
    private TextView mTvWallet,mTvTitle, mTvContent, mTvNumber, mTvPrice, mTvPayMoney;
    private RelativeLayout mRlWallet, mRlAddress;
    private TextView mTvNameAndTel, mTvAddress;
    private EditText mEtFeedBack;
    private List<ShopCarGoods> mShopCarGoodsList;
    //优惠后的价格(应付),已优惠的价格,/总额,总数,收货人名称,收货人电话,收货人地址
    private String mPayPrice,mDiscountPrice,mTotalPrice,mNumber,mReceiveName,mReceivePhone,mReceiveAddress,mAllValueReturn,mFeedBack;
    private PasswordDialog mPasswordDialog;
    @Inject
    ShopCarPayPresenter presenter;

    @Override
    protected int setView() {
        return R.layout.activity_order_pay;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        DaggerStoreComponent.builder()
                .appComponent(App.getInstance().getAppComponent())
                .storeModule(new StoreModule(this))
                .build()
                .inject(this);
        initView();
        initData();
    }

    private void initView() {
        isEnable(false);
        setTbTitle("订单支付");
        mTvWallet = getViewById(R.id.tv_wallet);
        mRgOrderPay = getViewById(R.id.rg_order_pay);
        mRgOrderPay.setOnCheckedChangeListener(this);
        mTvTitle = getViewById(R.id.tv_title);
        mTvContent = getViewById(R.id.tv_content);
        mTvNumber = getViewById(tv_number);
        mTvPrice = getViewById(R.id.tv_price);
        mTvPayMoney = getViewById(R.id.tv_pay_money);
        mRlWallet = getViewById(R.id.rl_wallet);
        mEtFeedBack = getViewById(R.id.et_feed_back);
        mTvNameAndTel = getViewById(R.id.tv_name_and_tel);
        mTvAddress = getViewById(R.id.tv_address);
        mRlAddress = getViewById(R.id.rl_address);
        RxUtils.bindEvents(mRlAddress, this);
        RxUtils.bindEvents(getViewById(R.id.btn_pay), this);
        registerPush();
    }


    private void initData() {
        Intent intent = getIntent();
        mStoreId = intent.getStringExtra("store_id");
        mStoreName = intent.getStringExtra("store_name");
        mStoreAddress = intent.getStringExtra("store_address");
        mShopCarGoodsList = (List<ShopCarGoods>) intent.getSerializableExtra("list");
        mPayPrice = intent.getStringExtra("pay_price");
        mDiscountPrice = intent.getStringExtra("discount_price");
        mTotalPrice = intent.getStringExtra("total_price");
        mNumber = intent.getStringExtra("number");
        mReceiveName = intent.getStringExtra("receive_name");
        mReceivePhone = intent.getStringExtra("receive_phone");
        mReceiveAddress = intent.getStringExtra("receive_address");
        mAllValueReturn = intent.getStringExtra("all_value_return");
        mFeedBack = intent.getStringExtra("feed_back");
        mTvPayMoney.setText("¥"+mPayPrice);
        mTvPrice.setText(mPayPrice);
        mTvNumber.setText(mNumber);
        //拿到最终支付的产品数量
        mTvAddress.setText(mReceiveAddress);
        mTvNameAndTel.setText(mReceiveName+mReceivePhone);
        mTvTitle.setText(mStoreName);
        mTvContent.setText("");
        if(InfoProvider.getUserAsset(this)==null){
            mTvWallet.setText("0.00");
        }else{
            mTvWallet.setText(InfoProvider.getUserAsset(this).getCash_balance());
        }
        presenter.getUserAsset();
    }

    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.btn_pay:
                if (mPayWay == 0) {
                    if(!StringUtils.moneyComp(mTvWallet.getText().toString(), mPayPrice)){
                        TipUtils.showToast(App.getInstance(),"可用零钱余额不足",2);
                        return;
                    }
                    UserToken userToken = InfoProvider.getUserToken(App.getInstance());
                    if (userToken.getSmall_direct_flag().equals("N") && userToken.getPayment_password_flag().equals("Y")) {
                        showPasswordDialog();
                    } else if (userToken.getSmall_direct_flag().equals("Y") && Float.parseFloat(mTvPayMoney.getText().toString().replace("¥", "")) > Constants.SMALL_AMOUNT && userToken.getPayment_password_flag().equals("Y")) {
                        showPasswordDialog();
                    } else {
                        presenter.orderPay(mPayWay,mStoreId,mStoreName,mReceiveName,mReceivePhone,mReceiveAddress,
                                mTotalPrice,mPayPrice,mAllValueReturn,mFeedBack, mShopCarGoodsList);
                    }
                }else{
                    presenter.orderPay(mPayWay,mStoreId,mStoreName,mReceiveName,mReceivePhone,mReceiveAddress,
                            mTotalPrice,mPayPrice,mAllValueReturn,mFeedBack, mShopCarGoodsList);
                }
                break;

        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {

        switch (checkedId) {
            case R.id.rb_wallet:    //零钱
                mPayWay = 0;
                break;
            case R.id.rb_alipay:   //支付宝
                mPayWay = 1;
                break;

            case R.id.rb_wechat:  //微信
                mPayWay = 2;
                break;


        }
    }
    private void registerPush() {
        Disposable subscribe = RxBus.get().toFlowable(PayResultBean.class).subscribe(new Consumer<PayResultBean>() {
            @Override
            public void accept(PayResultBean bean) throws Exception {
                if (bean != null) {
                    if (bean.result == Constants.PAY_RESULT_SUCCESS) {
                        TipUtils.showToast(App.getInstance(), "支付成功", 3);
                        RxBus.get().post(new EventBean(Constants.EVENT_TYPE_REFRESH));
                        finish();
                    }
                }
            }
        });
        mCompositeDisposable.add(subscribe);
    }
    /**
     * 零钱支付成功
     */
    @Override
    public void walletPaySuccess() {
        TipUtils.showToast(App.getInstance(),"零钱支付成功",3);
        RxBus.get().post(new EventBean(Constants.EVENT_TYPE_REFRESH));//钱包刷新
        finish();
    }

    @Override
    public void getUserAssetSuccess(UserAsset userAsset) {
        mTvWallet.setText(userAsset.getCash_balance());
    }

    @Override
    public void onFail(int code, String msg) {
        TipUtils.showToast(App.getInstance(),msg,2);
    }

    @Override
    protected void onRefreshData() {

    }

    @Override
    public void showError(String msg) {

    }

    /**
     * 显示
     */
    private void showPasswordDialog() {
        mPasswordDialog = new PasswordDialog(this, R.layout.dialog_payment_pwd);
        mPasswordDialog.setOnDialogPsdCompareListener(this);
        mPasswordDialog.show();
        mPasswordDialog.setPsdDescription("零钱支付");
        mPasswordDialog.setPsdContent(mTvPayMoney.getText().toString().replace("¥", ""));
    }

    /**
     * 成功验证密码
     * @param dialog
     */
    @Override
    public void onPasswordCorrect(PasswordDialog dialog) {
        mPasswordDialog.dismiss();
        presenter.orderPay(mPayWay,mStoreId,mStoreName,mReceiveName,mReceivePhone,mReceiveAddress,
                mTotalPrice,mPayPrice,mAllValueReturn,mFeedBack, mShopCarGoodsList);
    }

    @Override
    public void onPasswordError(PasswordDialog dialog, String msg) {
        TipUtils.showToast(App.getInstance(), getString(R.string.wallet_payment_setting_password_wrong));
        mPasswordDialog.clearInput();
    }
}
